﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title></title>
	<link href="js-console.css" rel="stylesheet" />
	<!-- 5. Write a function that counts how many times given 
			number appears in given array. Write a test function 
			to check if the function is working correctly.  -->
	<style>
		button {
			width: 800px;
		}

		strong {
			color: green;
		}
	</style>
</head>
<body>
	<button onclick="userInput()">Manage User Input</button>
	<button onclick="makeTests()">Test The Function</button>
	<div id="js-console"></div>
	<script src="js-console.js"></script>
	<script>
		function countAppearance(numbers, search) {
			var count = 0;

			for (var i in numbers) {
				if (numbers[i] == search) {
					count++;
				}
			}

			return count;
		}

		function makeTests() {
			var goodResults = 0;

			// 1.
			var result = countAppearance(new Array(1, 2, 3, 4, 5, 6, 7), 1);
			if (result == 1) {
				goodResults++;
			}

			// 2.
			var result = countAppearance(new Array(1, 1, 1, 1, 1, 1, 1), 1);
			if (result == 7) {
				goodResults++;
			}

			// 3.
			var result = countAppearance(new Array(1, 4, 3, 6, 8, 23, 1), 1);
			if (result == 2) {
				goodResults++;
			}

			// 4.
			var result = countAppearance(new Array(), 1);
			if (result == 0) {
				goodResults++;
			}

			// 5.
			var result = countAppearance([1], 1);
			if (result == 1) {
				goodResults++;
			}

			jsConsole.writeLine("From <strong>5</strong> tests there are <strong>" + goodResults +
								"</strong> correct results.");
		}

		function userInput() {
			var search = parseInt(prompt("Enter number to search"));
			var numbers = new Array();

			if (!isNaN(search)) {
				var input = prompt("Enter numbers separated by spaces");
				var array = input.split(' ');

				// Collect numbers only
				var j = 0;
				for (var i in array) {
					var num = parseInt(array[i]);
					if (!isNaN(num)) {
						numbers[j] = num;
						j++;
					}
				}
			}

			if (numbers.length > 0) {
				jsConsole.writeLine("Number " + search + " appears <strong>" +
									countAppearance(numbers, search) +
									"</strong> times in the array " +
									numbers.join());
			}
			else {
				jsConsole.writeLine("Wrong input");
			}
		}
	</script>
</body>
</html>
